package com.t.bricks.bussiness.service.flowwork.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.db.dao.flowwork.FlowWorkNodeDao;
import com.t.bricks.bussiness.db.entity.flowwork.FlowWorkNode;
import com.t.bricks.bussiness.service.flowwork.MonitoringService;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.json.JacksonShell;
import com.t.bricks.utils.function.url.HttpsUtil;

/**
 * 监听服务
 * @author HuangXinBian
 * @DateTime 2022年2月3日 下午1:21:26
 */
@Service
public class MonitoringServiceImpl implements MonitoringService {

	@Autowired
	private FlowWorkNodeDao<FlowWorkNode> flowWorkNodeDao;
	
	/**
	 * 最后执行时间
	 */
	private static LocalDateTime lastTime = null;
	
	/**
	 * 是否运行中
	 */
	private static int iState = 0;
	
	/**
	 * 启动(线程意外停止时使用)
	 * @return
	 */
	@Override
	@PostConstruct
	public MsgEmity start() {
		if (1 == iState) {
			return MsgEmity.success("执行中");
		}
		
		new Thread(() -> {
			iState = 1;
			while (1 == iState) {
				int i = doFlowWorkNode();//有可能刚结束又有
				if (i > 0) {
					continue;
				}
				
				try {
					Thread.sleep(5000);
				} catch (Exception e) {
					Log.error("线程发生异常:", e.getMessage());
				}
			}
			
			iState = 0;
		}).start();
		
		return null;
	}
	
	/**
	 * 查看信息
	 * @return
	 */
	@Override
	public MsgEmity info() {
		Map<String, Object> map = new HashMap<>(2);
		map.put("lastTime", lastTime);
		map.put("iState", iState);

		return MsgEmity.success(map, iState == 1 ? "运行中" : "已经停止");
	}
	
	/**
	 * 执行节点
	 * @return
	 */
	private int doFlowWorkNode() {
		MsgEmity me = flowWorkNodeDao.findByType3();
		if (!me.isSuccess()) {
			return 0;
		}
		
		List<FlowWorkNode> list = me.getData();
		if (1 > list.size()) {
			return 0;
		}
		
		while(list.size() > 0) {
			lastTime = LocalDateTime.now();
			FlowWorkNode flowWorkNode = list.get(0);
			
			//--如果有前置任务则需要进行调用--//
			if (null != flowWorkNode.getsPreviseApi() && null == flowWorkNode.getsPreviseResult()) {
				Map<String, String> map = new HashMap<>(2);
				map.put("uId", flowWorkNode.getuId());
				map.put("sWorkId", flowWorkNode.getsWorkId());
				
				String param = JacksonShell.toJSONString(map);
				me = HttpsUtil.get(flowWorkNode.getsPreviseApi(), param);
				if (!me.isSuccess() && flowWorkNode.getiPreviseResult().intValue() == 1) {
					list.remove(flowWorkNode);
					continue;
				}
				
				flowWorkNode.setsPreviseResultText(String.valueOf(me.getData()));
				if (0 < flowWorkNodeDao.editApiResult(flowWorkNode)) {
					list.remove(flowWorkNode);
					continue;
				}
				
				flowWorkNode.setiVersion(flowWorkNode.getiVersion() +1);
			}
			
			//--如果有当前任务则需要进行调用--//
			if (null != flowWorkNode.getsNodeApi() && null == flowWorkNode.getsNodeResult()) {
				Map<String, String> map = new HashMap<>(2);
				map.put("uId", flowWorkNode.getuId());
				map.put("sWorkId", flowWorkNode.getsWorkId());
				
				String param = JacksonShell.toJSONString(map);
				me = HttpsUtil.get(flowWorkNode.getsNodeApi(), param);
				if (!me.isSuccess() && flowWorkNode.getiNodeResult().intValue() == 1) {
					list.remove(flowWorkNode);
					continue;
				}
				
				flowWorkNode.setsPreviseResultText(String.valueOf(me.getData()));
				if (0 < flowWorkNodeDao.editApiResult(flowWorkNode)) {
					list.remove(flowWorkNode);
					continue;
				}
				
				flowWorkNode.setiVersion(flowWorkNode.getiVersion() +1);
			}

			//--如果有后置任务则需要进行调用--//
			if (null != flowWorkNode.getsBackApi() && null == flowWorkNode.getsBackResult()) {
				Map<String, String> map = new HashMap<>(2);
				map.put("uId", flowWorkNode.getuId());
				map.put("sWorkId", flowWorkNode.getsWorkId());
				
				String param = JacksonShell.toJSONString(map);
				me = HttpsUtil.get(flowWorkNode.getsBackApi(), param);
				if (!me.isSuccess() && flowWorkNode.getiBackResult().intValue() == 1) {
					list.remove(flowWorkNode);
					continue;
				}
				
				flowWorkNode.setsBackResult(String.valueOf(me.getData()));
				if (0 < flowWorkNodeDao.editApiResult(flowWorkNode)) {
					list.remove(flowWorkNode);
					continue;
				}
				
				flowWorkNode.setiVersion(flowWorkNode.getiVersion() +1);
			}
			
			list.remove(flowWorkNode);//无论任务是否执行成功,都要剔除当前队列,失败的让下一次查询后再进行
		}
		
		return 1;
	}
	
	
}
